#include "treesitter.h"

TreeSitterSelect::TreeSitterSelect() {
  tempDir = new QTemporaryDir();
  if (tempDir->isValid()) {
    pythonScriptPath = tempDir->path() + "/main.py";
    QFile file(pythonScriptPath);
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
      QTextStream out(&file);
      out << pythonScript;
      file.close();
    }
  }
}

TreeSitterSelect::~TreeSitterSelect() { delete tempDir; }

PyMsg TreeSitterSelect::execute(const QStringList &args) {
  PyMsg msg;
  if (!tempDir->isValid()) {
    msg.error = true;
    msg.msg = "Can't create temp dir.";
    return msg;
  }

  QProcess process;
  QStringList processArgs;
  processArgs << pythonScriptPath << args;
  process.start(pythonBinPath, processArgs);

  if (!process.waitForFinished()) {
    msg.error = true;
    msg.msg = "Python script not finished.";
    return msg;
  }

  QByteArray output = process.readAllStandardOutput();
  QByteArray errorOutput = process.readAllStandardError();

  if (!errorOutput.isEmpty()) {
    msg.error = true;
    msg.msg = errorOutput;
  } else
    msg.msg = output;

  return msg;
}

void TreeSitterSelect::setPythonBinPath(QString path) { pythonBinPath = path; }

